package com.hk.commons.validator;

import com.hk.commons.enums.AreaCodeEnum;
import com.hk.commons.util.StringUtils;
import com.hk.commons.validator.constraints.PhoneGroup;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import java.util.Arrays;

/**
 * @author kevin
 * @date 2021-04-02 11:27
 */
public class PhoneGroupValidator implements ConstraintValidator<PhoneGroup, CharSequence> {

    private boolean notEmpty;

    private AreaCodeEnum[] allowAreaCode;

    @Override
    public void initialize(PhoneGroup constraintAnnotation) {
        this.notEmpty = constraintAnnotation.notEmpty();
        this.allowAreaCode = constraintAnnotation.allowAreaCode();
    }

    @Override
    public boolean isValid(CharSequence value, ConstraintValidatorContext context) {
        return StringUtils.isEmpty(value) ? !notEmpty :
                Arrays.stream(allowAreaCode).anyMatch(item -> item.matcher(value));
    }
}
